
//
//  PCScatterViewController.m
//  wallet
//
//  Created by Alex on 2018/10/10.
//  Copyright © 2018年 ProChain. All rights reserved.
//

#import "PCScatterViewController.h"
#import "SignatureViewTool.h"
#import "EOSService.h"
#import "DappPushMshModel.h"
#import "SignatureForMessageModel.h"
#import "GetEosBalanceModel.h"
#import "GetTransactionByIdModel.h"
#import "XHPermissionsViewController.h"
#import "ShareView.h"
#import "AppDelegate+UMengHelper.h"
#import "HMScannerViewController.h"
#import "XKeyChainUDID.h"
#import "WKBridgeTool.h"
#import "WKWebViewJsBridge.h"
#import "HMScannerViewController.h"
#import "TZImagePickerController.h"
#define JS_INTERACTION_METHOD_PUSH @"push"
#define JS_INTERACTION_METHOD_PUSHACTION @"pushAction"
#define JS_INTERACTION_METHOD_PUSHACTIONS @"pushActions"
#define JS_INTERACTION_METHOD_PUSHMESSAGE @"pushMessage"

#define JS_INTERACTION_METHOD_walletLanguage @"walletLanguage"
#define JS_INTERACTION_METHOD_getEosAccount @"getEosAccount"
#define JS_INTERACTION_METHOD_getWalletWithAccount @"getWalletWithAccount"
#define JS_INTERACTION_METHOD_getEosBalance @"getEosBalance"
#define JS_INTERACTION_METHOD_getEosAccountInfo @"getEosAccountInfo"
#define JS_INTERACTION_METHOD_getTransactionById @"getTransactionById"
#define JS_INTERACTION_METHOD_pushActions @"pushActions"
#define JS_INTERACTION_METHOD_pushTransfer @"pushTransfer"
#define JS_INTERACTION_METHOD_getAppInfo @"getAppInfo"
#define JS_INTERACTION_METHOD_unknown @"unknown"

#define JS_INTERACTION_METHOD_requestSignature @"requestSignature"
#define JS_INTERACTION_METHOD_requestMsgSignature @"requestMsgSignature"


#define JS_METHODNAME_CALLBACKRESULT @"callbackResult"
#define JS_METHODNAME_PUSHACTIONRESULT @"pushActionResult"

#define JS_METHODNAME_SHARE @"share"
#define JS_METHODNAME_IosOpenCamera @"iosOpenCamera"
#define JS_METHODNAME_IosOpenCameraPicture @"iosOpenCameraPicture"
#define JS_METHODNAME_SaveIosPicture @"saveIosPicture"

@interface PCScatterViewController ()<WKNavigationDelegate,WKScriptMessageHandler>
@property (assign, nonatomic) int EOSNET_TYPE;
@property (nonatomic,strong) EOSService *eosService;
@property (nonatomic,strong) Wallet *wallet;
@property(nonatomic , strong) DappPushMshModel *dappPushMessageModel;
@property(nonatomic , strong) SignatureForMessageModel *signatureForMessageModel;;
@property (nonatomic, strong) WKWebViewJsBridge *jsBridge;

@end

@implementation PCScatterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self config];
    [self loadData];
}

- (void)reload{
    [self.webView reload];
}

- (void)config{
    if (!ProductSever) {
        self.jsBridge = [[WKWebViewJsBridge alloc] initWithWebView:self.webView delegate:self];
    }else{
        if ([self.dappInfo.address containsString:@".hnwxyxwl.cn"]) {
            self.jsBridge = [[WKWebViewJsBridge alloc] initWithWebView:self.webView delegate:self];
        }
    }
    self.wallet = CURRENT_WALLET;
    WKUserScript *userScript = [[WKUserScript alloc] initWithSource:[self getInjectJS] injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];// forMainFrameOnly:NO(全局窗口)，yes（只限主窗口）
    [self.webView.configuration.userContentController addUserScript:userScript];
    if (@available(iOS 9.0, *)) {
//        self.webView.customUserAgent = @"iOS";
    } else {
        // Fallback on earlier versions
    }
}

- (void)loadData {
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.dappInfo.address]]];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //注册js方法
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:JS_INTERACTION_METHOD_PUSHACTION];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:JS_INTERACTION_METHOD_PUSH];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:JS_INTERACTION_METHOD_PUSHACTIONS];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:JS_INTERACTION_METHOD_PUSHMESSAGE];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:JS_METHODNAME_SHARE];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:JS_METHODNAME_IosOpenCamera];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:JS_METHODNAME_IosOpenCameraPicture];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:JS_METHODNAME_SaveIosPicture];

}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:JS_INTERACTION_METHOD_PUSHACTION];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:JS_INTERACTION_METHOD_PUSH];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:JS_INTERACTION_METHOD_PUSHACTIONS];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:JS_INTERACTION_METHOD_PUSHMESSAGE];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:JS_METHODNAME_SHARE];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:JS_METHODNAME_IosOpenCamera];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:JS_METHODNAME_IosOpenCameraPicture];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:JS_METHODNAME_SaveIosPicture];
}

- (NSString *)getInjectJS{
    NSString *JSfilePath = [[NSBundle mainBundle]pathForResource:@"scatter_src" ofType:@"js"];
    NSString *content = [NSString stringWithContentsOfFile:JSfilePath encoding:NSUTF8StringEncoding error:nil];
    NSString *final = [@"var script = document.createElement('script');"
                       "script.type = 'text/javascript';"
                       "script.text = \""
                       stringByAppendingString:content];
    return final;
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    [super webView:webView didFinishNavigation:navigation];

//    [self passEosAccountNameToJS];
//    [self passWalletInfoToJS];
////    // 确保js 能收到 eosAccountName
//    kWeakSelf(self);
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [weakself passEosAccountNameToJS];
//        [weakself passWalletInfoToJS];
//    });
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [weakself passEosAccountNameToJS];
//        [weakself passWalletInfoToJS];
//    });
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [weakself passEosAccountNameToJS];
//        [weakself passWalletInfoToJS];
//    });
//    [self.eosService getAccountInfoComplete:^(BOOL success, NSString * _Nonnull errorMsg) {
//        if (success) {
//            
//        }
//    }];
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    NSString *toast = (!image || error)? [NSString stringWithFormat:@"保存图片失败 , 错误：%@",error] : @"保存图片成功";
    [self.view makeToast:toast duration:2.0 position:CSToastPositionCenter];
}
//实现js调用ios的handle委托
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSLog(@"name:%@\\\\n body:%@\\\\n",message.name,message.body);
    NSDictionary* dict = (NSDictionary*)message.body;
    if ([message.name isEqualToString:JS_METHODNAME_SHARE]) {
        [ShareView showCallback:^(ShareType type) {
            UMSocialPlatformType umSocialPlatformType = type+1;
            NSString *title = dict[@"title"];
            NSString *ps = dict[@"ps"];
            NSString *thumbImage = self.dappInfo.imgUrl;
            NSString *url = dict[@"url"];
            [kAppDelegate shareWebPageToPlatformType:umSocialPlatformType shareTitle:title subTitle:ps thumbImage:thumbImage shareURL:url completion:^(BOOL success) {
//                if (success) {
//                    [kAppWindow makeToast:XLocalized(@"分享成功")];
//                }else{
//                    [kAppWindow makeToast:XLocalized(@"分享失败")];
//                }
            }];
        }];
        return;
    }
    ///保存图片
    if ([message.name isEqualToString:JS_METHODNAME_SaveIosPicture]) {
          ///
        kWeakSelf(self);
        NSString *dataStr = message.body;
         dataStr = [dataStr stringByReplacingOccurrencesOfString:@"data:image/png;base64," withString:@""];
                NSData *aData = [NSData dataWithBase64EncodedString: dataStr];
            UIImage *image = [UIImage imageWithData:aData];
                 UIImageWriteToSavedPhotosAlbum(image, weakself, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
           return;
       }
    ///选择图片
    if ([message.name isEqualToString:JS_METHODNAME_IosOpenCameraPicture]) {
       ///
        DLog(@" dict %@",NSStringFromClass(dict.class));
        BOOL crop = NO;
        if ([dict isKindOfClass:NSNumber.class]) {
            crop = [(NSNumber*)dict boolValue];
            NSLog(@"crop %d",crop);
        }
     
        TZImagePickerController *picker = [TZImagePickerController new];
                 picker.maxImagesCount=1;
                 picker.showSelectBtn = NO;
                 picker.allowCrop = crop;
                 picker.cropRect = CGRectMake(0, (kScreenHeight-kScreenWidth)*.5, kScreenWidth, kScreenWidth);
                 picker.allowPickingVideo = NO;
                 picker.didFinishPickingPhotosHandle = ^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                     UIImage *icon = [photos firstObject];
                     if (icon) {
                         NSData *data = UIImageJPEGRepresentation(icon, 0.01f);
                         NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithCarriageReturn];
                         NSString *jsStr = [NSString stringWithFormat:@"iosOpenCameraPictureResult('%@')", [encodedImageStr stringByRemovingPercentEncoding] ];
                                   [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
                                       NSLog(@"%@----%@",result, error);
                                   }];
                     }
                     
                     
                 };
                 [kCurrentVC.navigationController presentViewController:picker animated:YES completion:nil];
        return;
    }
    if ([message.name isEqualToString:JS_METHODNAME_IosOpenCamera]) {
        ///扫描二维码
        HMScannerViewController *scanner = [[HMScannerViewController alloc] initWithCardName:nil avatar:nil completion:^(NSString *stringValue) {
            NSString *jsStr = [NSString stringWithFormat:@"openCameraResultIos('%@')", [stringValue stringByRemovingPercentEncoding]];
            [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
                NSLog(@"%@----%@",result, error);
            }];
        }closeCompletion:^{

        } ];
        [kCurrentVC.navigationController pushViewController:scanner animated:YES];
        return;
    }
    //{{scatter support
    if ([message.name isEqualToString:JS_INTERACTION_METHOD_PUSHACTION] || [message.name isEqualToString:JS_INTERACTION_METHOD_PUSH]) {
//        self.dappTransferResult = [DappTransferResult mj_objectWithKeyValues:self.WKScriptMessageBody];
//        self.dappTransferModel = (DappTransferModel *)[DappTransferModel mj_objectWithKeyValues:[self.dappTransferResult.message mj_JSONObject ] ];
//        [self.view addSubview:self.loginPasswordView];
        
    }else if ([message.name isEqualToString:JS_INTERACTION_METHOD_PUSHACTIONS]){
//        self.dAppExcuteMutipleActionsResult = [DAppExcuteMutipleActionsResult mj_objectWithKeyValues:self.WKScriptMessageBody];
//        [self buildExcuteActionsDataSource];
    }else if ([message.name isEqualToString:JS_INTERACTION_METHOD_PUSHMESSAGE]){
        
        self.dappPushMessageModel = [DappPushMshModel modelWithJSON:dict];

        if([self.dappPushMessageModel.methodName isEqualToString:JS_INTERACTION_METHOD_getWalletWithAccount])
        {
            [self scatter_getIdentity];
        }
        else if ([self.dappPushMessageModel.methodName isEqualToString:JS_INTERACTION_METHOD_requestSignature]) {
            NSData *jsonData = [self.dappPushMessageModel.params dataUsingEncoding:NSUTF8StringEncoding];
            NSError *err;
            NSDictionary *actionsDict = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                        options:NSJSONReadingAllowFragments
                                                                          error:&err];
            if(err)
            {
                //decode json fail.
                return;
            }
            TransactionModel *transaction = [TransactionModel modelWithJSON:actionsDict[@"transaction"]];
            if (transaction) {
                SignatureModel*signatureModel =[transaction.actions firstObject];
                self.eosService.ref_block_num = transaction.ref_block_num;
                self.eosService.ref_block_prefix = transaction.ref_block_prefix;
                self.eosService.expiration = transaction.expiration;
                self.eosService.binargs = signatureModel.data;
                [self scatter_transaction:self.dappPushMessageModel.serialNumber withParams:signatureModel];
                
            }
        }else if([self.dappPushMessageModel.methodName isEqualToString:JS_INTERACTION_METHOD_getAppInfo]){
            
        }else if([self.dappPushMessageModel.methodName isEqualToString:JS_INTERACTION_METHOD_walletLanguage]){
            [self js_pushMessage_method_walletLanguage];
        }else if([self.dappPushMessageModel.methodName isEqualToString:JS_INTERACTION_METHOD_getEosBalance]){
            [self js_pushMessage_method_getEosBalance];
        }else if([self.dappPushMessageModel.methodName isEqualToString:JS_INTERACTION_METHOD_getEosAccountInfo]){
            
        }else if([self.dappPushMessageModel.methodName isEqualToString:JS_INTERACTION_METHOD_getTransactionById]){
            [self js_pushMessage_method_getTransactionById];
        }else if([self.dappPushMessageModel.methodName isEqualToString:JS_INTERACTION_METHOD_pushActions]){
            
        }else if([self.dappPushMessageModel.methodName isEqualToString:JS_INTERACTION_METHOD_pushTransfer]){
            
        }else if([self.dappPushMessageModel.methodName isEqualToString:JS_INTERACTION_METHOD_requestMsgSignature]){
            [self generateSignatureForMessage];
        }else{
            [self js_pushMessage_method_unknown];
        }
    }
}
///回调dappWeb
- (void)responseToJsWithJSMethodName:(NSString *)jsMethodName SerialNumber:(NSString *)serialNumber andMessage:(NSString *)message{
    NSString *jsStr = [NSString stringWithFormat:@"%@('%@', '%@')", jsMethodName,serialNumber, message];
    NSLog(@"responseToJs %@", jsStr);
    [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSLog(@"%@----%@",result, error);
    }];
}

///获取登录账号
-(void)scatter_getIdentity{
    
    NSMutableDictionary *walletDict = [[NSMutableDictionary alloc] init];
    NSMutableDictionary *dataDict = [[NSMutableDictionary alloc] init];
    [dataDict setValue:self.wallet.wallet_name forKey:@"account"];
    //    [dataDict setValue:self.wallet.wallet_uid forKey:@"uid"];
    //    [dataDict setValue:self.wallet.wallet_name forKey:@"wallet_name"];
    [dataDict setValue:self.wallet.wallet_public_key forKey:@"active_public_key"];
    [dataDict setValue:self.wallet.wallet_system forKey:@"chainType"];
    [dataDict setValue:self.wallet.permission?:@"active" forKey:@"authority"];
    //    [walletDict setValue:@0 forKey:@"code"];
    //    [walletDict setValue:@"success" forKey:@"message"];
    [walletDict setValue:dataDict forKey:@"data"];
    //    [walletDict setValue:@"onwer" forKey:@"permission"];
    [self responseToJsWithJSMethodName:JS_METHODNAME_CALLBACKRESULT SerialNumber:self.dappPushMessageModel.serialNumber andMessage:[walletDict modelToJSONString]];
    
    kWeakSelf(self);
    [self.eosService getAccountInfoComplete:^(BOOL success, NSString * _Nonnull errorMsg) {
        if (success) {
            if (!self.eosService.permission.length) {
                [XAlertTool alertTitle:@"提示" message:@"当前账号权限已经变更，前往查看账号权限是否正常？" cancelAction:^{
                } sureAction:^{
                    XHPermissionsViewController *vc = [XHPermissionsViewController new];
                    vc.wallet = weakself.eosService.wallet;
                    [weakself.navigationController pushViewController:vc animated:YES];
                }];
                return;
            }
            NSMutableDictionary *walletDict = [[NSMutableDictionary alloc] init];
            NSMutableDictionary *dataDict = [[NSMutableDictionary alloc] init];
            [dataDict setValue:self.wallet.wallet_name forKey:@"account"];
            //[dataDict setValue:self.wallet.wallet_uid forKey:@"uid"];
            //[dataDict setValue:self.wallet.wallet_name forKey:@"wallet_name"];
            [dataDict setValue:self.wallet.wallet_public_key forKey:@"active_public_key"];
            [dataDict setValue:self.wallet.wallet_system forKey:@"chainType"];
            [dataDict setValue:self.wallet.permission?:@"active" forKey:@"authority"];
            //    [walletDict setValue:@0 forKey:@"code"];
            //    [walletDict setValue:@"success" forKey:@"message"];
            [walletDict setValue:dataDict forKey:@"data"];
            //    [walletDict setValue:@"onwer" forKey:@"permission"];
            [self responseToJsWithJSMethodName:JS_METHODNAME_CALLBACKRESULT SerialNumber:self.dappPushMessageModel.serialNumber andMessage:[walletDict modelToJSONString]];
            [[XHDataBaseManager shareInstance]updateWalletToDB:self.wallet];
        }
    }];
}
- (void)passWalletInfoToJS{
    NSMutableDictionary *walletDict = [[NSMutableDictionary alloc] init];
    NSMutableDictionary *dataDict = [[NSMutableDictionary alloc] init];
    [dataDict setValue:self.wallet.wallet_name forKey:@"account"];
    [dataDict setValue:self.wallet.wallet_uid forKey:@"uid"];
    [dataDict setValue:self.wallet.wallet_name forKey:@"wallet_name"];
    [dataDict setValue:self.wallet.wallet_public_key forKey:@"active_public_key"];
    [dataDict setValue:self.wallet.wallet_system forKey:@"chainType"];
    [walletDict setValue:@0 forKey:@"code"];
    [walletDict setValue:@"success" forKey:@"message"];
    [walletDict setValue:dataDict forKey:@"data"];
    NSString *js = [NSString stringWithFormat:@"getWalletWithAccount('%@')",[walletDict modelToJSONString]];
    [self.webView evaluateJavaScript:js completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        //TODO
        NSLog(@"%@ ",response);
    }];
}

- (void)js_pushMessage_method_getTransactionById{
    kWeakSelf(self);
    GetTransactionByIdModel *model = [GetTransactionByIdModel modelWithJSON:self.dappPushMessageModel.params];
    self.eosService.transaction_id = model.txid;
    [self.eosService getTransactionDetailInfoComplete:^(BOOL success, XHBaseModel *data, NSString * _Nonnull errorMsg) {
        NSMutableDictionary *resultDict = [[NSMutableDictionary alloc] init];
        [resultDict setValue: data.data?:@"" forKey:@"data"];
        [resultDict setValue: VALIDATE_NUMBER(data.errNo) forKey:@"code"];
        [resultDict setValue:VALIDATE_STRING(data.errmsg) forKey:@"message"];
        [weakself responseToJsWithJSMethodName:JS_METHODNAME_CALLBACKRESULT SerialNumber:weakself.dappPushMessageModel.serialNumber andMessage:[resultDict modelToJSONString]];
    }];
}

- (void)passEosAccountNameToJS{
    NSString *js = [NSString stringWithFormat:@"getEosAccount('%@')", self.wallet.wallet_name];
    [self.webView evaluateJavaScript:js completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        //TODO
        NSLog(@"%@ ",response);
    }];
}

- (void)alertPassword{
    
    
}
- (void)generateSignatureForMessage{
    self.signatureForMessageModel = [SignatureForMessageModel modelWithJSON:self.dappPushMessageModel.params];
    if (![self.wallet.wallet_public_key isEqualToString:self.signatureForMessageModel.publicKey]) {
        NSMutableDictionary *resultDict = [[NSMutableDictionary alloc] init];
        [resultDict setValue: NSLocalizedString(@"请求授权账户和本地账户不同,请谨慎操作", nil)  forKey:@"data"];
        [resultDict setValue: @1 forKey:@"code"];
        [resultDict setValue:@"error" forKey:@"message"];
        [self responseToJsWithJSMethodName:JS_METHODNAME_CALLBACKRESULT SerialNumber:self.dappPushMessageModel.serialNumber andMessage: [resultDict modelToJSONString]];
        return;
    }
    [LEEAlert actionsheet].config
    .LeeAddTitle(^(UILabel *label) {
        label.text = XLocalized(@"账号授权");
        label.textColor = UIColorHex(666666);
        label.textAlignment = NSTextAlignmentCenter;
    })
    .LeeAddTitle(^(UILabel *label) {
        label.text = [NSString stringWithFormat:@"%@:%@",XLocalized(@"账号名称"),self.wallet.wallet_name];
        label.textColor = [UIColor darkGrayColor];
        label.textAlignment = NSTextAlignmentLeft;
    })
    .LeeAddContent(^(UILabel *label) {
        label.text = [NSString stringWithFormat:@"%@:%@",XLocalized(@"备注"),self.signatureForMessageModel.whatfor];;
        label.textColor = [[UIColor redColor] colorWithAlphaComponent:0.5f];
        label.textAlignment = NSTextAlignmentLeft;
    })
    .LeeAction(@"好的", ^{
        [self.eosService excuteSignatureMessageForScatterWithActor:self.wallet signatureMessage:self.signatureForMessageModel.data complete:^(BOOL success, NSString * _Nonnull signatureStr) {
            if (success) {
                NSMutableDictionary *finalDict = [NSMutableDictionary dictionary];
                [finalDict setObject:@0 forKey:@"code"];
                [finalDict setObject:VALIDATE_STRING(signatureStr) forKey:@"data"];
                [finalDict setObject:@"Signed" forKey:@"message"];
                DLog(@"%@",finalDict);;
                [self responseToJsWithJSMethodName:JS_METHODNAME_CALLBACKRESULT SerialNumber:self.dappPushMessageModel.serialNumber andMessage:[finalDict modelToJSONString]];
            }else{
                [self responseToJsWithJSMethodName:JS_METHODNAME_CALLBACKRESULT SerialNumber:self.dappPushMessageModel.serialNumber andMessage: [[self handleResponseToJsErrorInfoWithErrorMessage:@"ERROR:CANCLE" serialNumber:self.dappPushMessageModel.serialNumber] modelToJSONString]];
            }
        }];
    })
    .LeeCancelAction(@"取消", ^{
         [self responseToJsWithJSMethodName:JS_METHODNAME_CALLBACKRESULT SerialNumber:self.dappPushMessageModel.serialNumber andMessage: [[self handleResponseToJsErrorInfoWithErrorMessage:@"ERROR:CANCLE" serialNumber:self.dappPushMessageModel.serialNumber] modelToJSONString]];
    })
    .LeeShow();

}
///请求签名
-(void)scatter_transaction:(NSString*)serialNumber withParams:(SignatureModel*)signatureModel
{
    kWeakSelf(self);
    NSDictionary *parame = @{@"code":VALIDATE_STRING(signatureModel.account),@"action":VALIDATE_STRING(signatureModel.name),@"binargs":VALIDATE_STRING(signatureModel.data)};
    [MBProgressHUD showLoadTitile:@"" ToView:self.view];
    [self.eosService abiBinJsonToParameters:parame complete:^(BOOL success, NSString * _Nonnull errorMsg, NSDictionary * _Nonnull json) {
        [MBProgressHUD hideHUDForView:self.view];
        if (success) {
            signatureModel.jsonData = json;
            [WalletTool checkPrivateInputDapp:self.dappInfo signatureModel:signatureModel PasswordWith:self.wallet complete:^(BOOL result, NSString * _Nonnull privateKey, SignatureModel * _Nonnull signatureModel) {
                if (result) {
                    [[SignatureViewTool sharedSignatureViewTool]dissmiss];
                    weakself.eosService.privateKey = privateKey;
                    weakself.eosService.action = signatureModel.name;
                    weakself.eosService.actor = self.wallet.wallet_name;
                    weakself.eosService.account = signatureModel.account;
                    weakself.eosService.available_keys = @[VALIDATE_STRING(self.wallet.wallet_public_key)];
                    //            [MBProgressHUD showLoadTitile:@"" ToView:weakself.view];
                    weakself.eosService.chain_id = [NSObject convertHexStrToData:@"aca376f206b8fc25a6ed44dbdc66547c36c6c33e3a119ffbeaef943642f0e906"];
//                    [self.eosService getAccountInfoComplete:^(BOOL success, NSString * _Nonnull errorMsg) {
//                        if (success) {
//                            [self.eosService.accountResult.permissions enumerateObjectsUsingBlock:^(EOSPermissionsInfo * _Nonnull permissions, NSUInteger idx, BOOL * _Nonnull stopAll) {
//                                if (permissions) {
//                                    [permissions.required_auth.keys enumerateObjectsUsingBlock:^(EOSKey * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//                                        if ([obj.key isEqualToString:self.wallet.wallet_public_key]) {
//                                            self.eosService.permission = permissions.perm_name;
//                                            *stop = YES;
//                                            *stopAll=YES;
//                                        }
//                                    }];
//                                }
//                            }];
//                            if ([self.eosService.permission isEqualToString:@"active"]) {
                                [self.eosService signTransactionComplete:^(NSString * _Nonnull signatureStr) {
                                    if (signatureStr) {
                                        NSMutableDictionary *finalDict = [NSMutableDictionary dictionary];
                                        NSMutableDictionary *dataDict = [NSMutableDictionary dictionary];
                                        NSMutableDictionary *signDataDict = [NSMutableDictionary dictionary];
                                        [signDataDict setObject:[NSDictionary dictionary] forKey:@"returnedFields"];
                                        [signDataDict setObject:@[VALIDATE_STRING(signatureStr)] forKey:@"signatures"];
                                        [dataDict setObject:signDataDict forKey:@"signData"];
                                        [dataDict setObject:serialNumber forKey:@"serialNumber"];
                                        [finalDict setObject:dataDict forKey:@"data"];
                                        [finalDict setObject:@"success" forKey:@"message"];
                                        [finalDict setObject:@0 forKey:@"code"];
                                        
                                        NSLog(@"ScatterResponseToJSfinalJson %@", [finalDict modelToJSONString]);
                                        [self responseToJsWithJSMethodName:JS_METHODNAME_CALLBACKRESULT SerialNumber:serialNumber
                                                                andMessage:[finalDict modelToJSONString]];
                                    }
                                }];
//                            }else{
//                                [XAlertTool alertTitle:@"提示" message:@"当前权限不是Active，或者权限不足,操作失败" cancelAction:nil sureAction:^{
//
//                                }];
//                                [self responseToJsWithJSMethodName:JS_METHODNAME_CALLBACKRESULT SerialNumber:serialNumber andMessage: [[self handleResponseToJsErrorInfoWithErrorMessage:@"ERROR:CANCLE" serialNumber:serialNumber] modelToJSONString]];
//                            }}{
//                                 [self responseToJsWithJSMethodName:JS_METHODNAME_CALLBACKRESULT SerialNumber:serialNumber andMessage: [[self handleResponseToJsErrorInfoWithErrorMessage:@"ERROR:CANCLE" serialNumber:serialNumber] modelToJSONString]];
//                            }}];
               
                    //            weakself.eosService.ref_block_num = [NSString stringWithFormat:@"%@",chainInfo.head_block_num];
                    //            weakself.eosService.chain_id = [NSObject convertHexStrToData:chainInfo.chain_id];
                    //            weakself.eosService.expiration = [[[NSDate dateFromString: chainInfo.head_block_time] dateByAddingTimeInterval: 30] formatterToISO8601];
                    
                }else{
                    ///h取消操作
                    [self responseToJsWithJSMethodName:JS_METHODNAME_CALLBACKRESULT SerialNumber:serialNumber andMessage: [[self handleResponseToJsErrorInfoWithErrorMessage:@"ERROR:CANCLE" serialNumber:serialNumber] modelToJSONString]];
                    
                }
            }];
        }
    }];
   
}
- (void)js_pushMessage_method_walletLanguage{
    NSMutableDictionary *resultDict = [[NSMutableDictionary alloc] init];
    [resultDict setValue:@0 forKey:@"code"];
    [resultDict setValue:VALIDATE_STRING(@"success") forKey:@"message"];
    if ([kXAppLanguageName isEqualToString:kHansLanguage]) {
        [resultDict setValue:@"Chinese" forKey:@"data"];
    }else{
        [resultDict setValue:@"English" forKey:@"data"];
    }
    [self responseToJsWithJSMethodName:JS_METHODNAME_CALLBACKRESULT SerialNumber:self.dappPushMessageModel.serialNumber andMessage:[resultDict modelToJSONString]];
}
- (void)js_pushMessage_method_getEosBalance{
    GetEosBalanceModel *model = [GetEosBalanceModel modelWithJSON:self.dappPushMessageModel.params];
  
    kWeakSelf(self);
    [self.eosService getAccountCurrencyBalanceCode:model.contract account:model.account symbol:@"" complete:^(BOOL success, NSString * _Nonnull errorMsg, TokenInfo * _Nonnull tokenInfo) {
        [weakself responseToJsWithJSMethodName:JS_METHODNAME_CALLBACKRESULT SerialNumber:weakself.dappPushMessageModel.serialNumber andMessage:tokenInfo.balance];
    }];

}

- (NSMutableDictionary *)handleResponseToJsErrorInfoWithErrorMessage:(NSString *)errorMessage serialNumber:(NSString*)serialNumber{
    NSMutableDictionary *resultDict = [[NSMutableDictionary alloc] init];
    NSMutableDictionary *dataDict = [[NSMutableDictionary alloc] init];
    [dataDict setValue: VALIDATE_STRING(serialNumber) forKey:@"serialNumber"];
    [dataDict setValue: VALIDATE_STRING(errorMessage) forKey:@"errorMsg"];
    [resultDict setValue:VALIDATE_NUMBER(@1) forKey:@"code"];
    [resultDict setValue:VALIDATE_STRING(errorMessage) forKey:@"message"];
    [resultDict setValue:dataDict forKey:@"data"];
    return resultDict;
}

- (void)js_pushMessage_method_unknown{
    NSMutableDictionary *resultDict = [[NSMutableDictionary alloc] init];
    [resultDict setValue:@0 forKey:@"code"];
    [resultDict setValue:VALIDATE_STRING(@"Not support") forKey:@"message"];
    [resultDict setValue:VALIDATE_STRING(@"") forKey:@"data"];
    [self responseToJsWithJSMethodName:JS_METHODNAME_CALLBACKRESULT SerialNumber:self.dappPushMessageModel.serialNumber andMessage:[resultDict modelToJSONString]];
}

#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    DLog(@"alert === %@",message);
//    completionHandler();
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)dealloc{
    _jsBridge = nil;
}
#pragma mark - getter
- (EOSService*)eosService{
    if (!_eosService) {
        _eosService = [EOSService new];
    }
    return _eosService;
}

#pragma mark - private


@end
